<utask-loader *ngIf="(loaders.task || loaders.resolution) && !errors.main"></utask-loader>
<lib-utask-error-message [data]="errors.main" *ngIf="errors.main"></lib-utask-error-message>
<ng-container *ngIf="((!loaders.task && !loaders.resolution)) && !errors.main">
    <nz-page-header nzBackIcon [nzGhost]="false">
        <nz-page-header-title><span class="bloc_status task_state_{{(task$ | async).state}}">{{(task$ | async).state}}</span> {{(task$ | async).title}}
        </nz-page-header-title>
        <nz-page-header-extra>
            <span>Autorefresh (5s)</span>
            <nz-switch [(ngModel)]="autorefresh.actif" [nzDisabled]="!autorefresh.enable"
                (ngModelChange)="autorefresh.hasChanged = true">
            </nz-switch>
            <button type="button" nz-button nzType="primary" nzShape="circle" nzSize="small" (click)="loadTask(true)"
                title="Refresh tasks"
                [nzLoading]="loaders.task || loaders.resolution || loaders.refreshResolution || loaders.refreshTask"
                [disabled]="autorefresh.actif"><i nz-icon nzType="sync"></i></button>
        </nz-page-header-extra>
    </nz-page-header>

    <!-- Template description -->
    <nz-alert *ngIf="template && (template.long_description || template.doc_link)" nzType="info"
        [nzMessage]="templateInfoMessage" nzShowIcon class="template-description"></nz-alert>
    <ng-template #templateInfoMessage>
        <p *ngIf="template.long_description" style="white-space: pre-line;">
            {{template.long_description}}
            <ng-container *ngIf="template.doc_link">
                <br /><a href="{{template.doc_link}}" target="_blank">{{template.doc_link}}</a>
            </ng-container>
        </p>
    </ng-template>

    <!-- Task info -->
    <nz-descriptions class="task-description" *ngIf="(task$ | async).tags" nzBordered [nzSize]="'small'" [nzColumn]="1">
        <nz-descriptions-item *ngIf="(task$ | async)?.tags?._utask_parent_task_id" nzTitle="Parent task">
            <a [routerLink]="[uiBaseUrl, 'task', (task$ | async).tags._utask_parent_task_id]">
                {{(task$ | async).tags._utask_parent_task_id}}
            </a>
        </nz-descriptions-item>
        <nz-descriptions-item *ngIf="(task$ | async).tags" nzTitle="Tags">
            <table>
                <tbody>
                    <tr *ngFor="let tagKey of objectKeys((task$ | async).tags)">
                        <td>{{tagKey}}</td>
                        <td>{{(task$ | async).tags[tagKey]}}</td>
                    </tr>
                </tbody>
            </table>
        </nz-descriptions-item>
    </nz-descriptions>

    <!-- Result box -->
    <lib-utask-box [header]="{openable: true, init: display.result, class: 'primary'}"
        *ngIf="(task$ | async).result && (task$ | async).resolution">
        <div app-box-header>Result</div>
        <div app-box-content>
            <lib-utask-editor [ngModel]="taskJson" ngDefaultControl [ngModelOptions]="{standalone: true}"
                [config]="{ language: 'json', readOnly: true, wordWrap: 'on' }">
            </lib-utask-editor>
        </div>
    </lib-utask-box>

    <!-- Request box -->
    <lib-utask-box [header]="{openable: true, init: display.request, class: 'primary'}">
        <div app-box-header>
            Request - {{(task$ | async).id}}
        </div>
        <nz-button-group app-box-header-extra>
            <button type="button" nz-button nzSize="small" title="View as code" (click)="previewTask(); $event.stopPropagation();">
                <i nz-icon nzType="file-text"></i>
            </button>
            <button type="button" nz-button nzSize="small" title="Edit the task" (click)="editRequest(); $event.stopPropagation();" [disabled]="!(canEditRequest$ | async)">
                <i nz-icon nzType="edit"></i>
            </button>
            <button type="button" nz-button nzSize="small" title="Delete the task" (click)="deleteTask(); $event.stopPropagation();" [disabled]="!(canDeleteRequest$ | async)">
                <i nz-icon nzType="delete"></i>
            </button>
        </nz-button-group>
        <div app-box-content>
            <nz-descriptions *ngIf="(task$ | async).input" nzBordered [nzSize]="'small'" [nzColumn]="1">
                <nz-descriptions-item nzTitle="Template">
                    <a [routerLink]="[uiBaseUrl, 'template', (task$ | async).template_name]"
                        title="Template {{(task$ | async).template_name}}" *ngIf="(meta$ | async).user_is_admin">
                        {{(task$ | async).template_name}}
                    </a>
                    <span *ngIf="!(meta$ | async).user_is_admin">{{(task$ | async).template_name}}</span>
                </nz-descriptions-item>
                <nz-descriptions-item *ngIf="(task$ | async) as task" nzTitle="Inputs" class="inputs">
                    <div *ngFor="let inputKey of objectKeys(task.input)" class="input">
                        <span class="key">{{ inputKey }}</span>
                        <span class="value">{{task.input[inputKey] | json}}</span>
                    </div>
                </nz-descriptions-item>
                <nz-descriptions-item nzTitle="Information">
                    Created by {{(task$ | async).requester_username}} <abbr
                        title="{{(task$ | async).created | date : 'yyyy/MM/dd HH:mm'}}"><em>{{(task$ | async).created |
                            utaskFromNow}}</em></abbr>
                    <span
                        *ngIf="(task$ | async).created != (task$ | async).last_activity || (task$ | async).requester_username != (task$ | async).resolver_username">
                        and
                        updated {{(task$ | async).resolver_username ? 'by' : ''}} {{(task$ | async).resolver_username}} <abbr
                            title="{{(task$ | async).last_activity | date : 'yyyy/MM/dd HH:mm'}}"><em>{{(task$ | async).last_activity |
                                utaskFromNow}}</em></abbr></span>
                </nz-descriptions-item>
            </nz-descriptions>
        </div>
    </lib-utask-box>

    <ng-container *ngIf="!display.restartTask">

        <!-- Execution box -->
        <lib-utask-box [header]="{openable: true, init: display.execution, class: 'primary'}"
            *ngIf="resolution$ | async as resolution">
            <div app-box-header>
                Execution -
                <small>{{resolution.id}}</small> -
                <small class="bloc_status resolution_state_{{resolution.state}}">{{resolution.state}}{{resolution.state === 'ERROR' ? ' (retrying)' : ''}}</small>
                <span *ngIf="loaders.execution || loaders.refreshTask">&nbsp;<i nz-icon nzType="loading"></i></span>
            </div>
            <div app-box-header-extra>
                <nz-button-group nzSize="small">
                    <button type="button" nz-button nzSize="small" title="Run the waiting steps" (click)="$event.stopPropagation(); runResolution(resolution)" [disabled]="!(canRun$ | async)">
                        <i nz-icon nzType="caret-right"></i>
                    </button>
                    <button type="button" nz-button nzSize="small" title="Start over the task" (click)="$event.stopPropagation(); display.restartTask = true" [disabled]="!(canStartOver$ | async)">
                        <i nz-icon nzType="rollback"></i>
                    </button>
                    <button type="button" nz-button nzSize="small" title="Cancel the resolution" (click)="$event.stopPropagation(); cancelResolution(resolution)" [disabled]="!(canCancel$ | async)">
                        <i nz-icon nzType="stop"></i>
                    </button>
                    <button type="button" nz-button nz-dropdown [nzDropdownMenu]="menu" [nzPlacement]="'bottomRight'" (click)="$event.stopPropagation()">More</button>
                </nz-button-group>
                <nz-dropdown-menu #menu="nzDropdownMenu">
                    <ul nz-menu>
                        <li nz-menu-item (click)="previewResolution()">View as code</li>
                        <li nz-menu-item [nzDisabled]="!(canPause$ | async)" (click)="pauseResolution(resolution)">Pause</li>
                        <li nz-menu-item [nzDisabled]="!(canExtend$ | async)" (click)="extendResolution(resolution)">Extend</li>
                        <li nz-menu-item [nzDisabled]="!(canEdit$ | async)" (click)="editResolution(resolution)">Edit</li>
                    </ul>
                </nz-dropdown-menu>
            </div>
            <pre>{{resolution|json}}</pre>
            <div app-box-content>
                <div nz-row [nzGutter]="16">
                    <div nz-col [nzSpan]="8">
                        <nz-descriptions nzBordered [nzSize]="'small'" [nzColumn]="1">
                            <nz-descriptions-item nzTitle="Execution instance">
                                #{{resolution.instance_id}} resolved by {{resolution.resolver_username}}
                            </nz-descriptions-item>
                            <nz-descriptions-item nzTitle="Last start">
                                {{resolution.last_start | date: 'yyyy/MM/dd HH:mm'}}
                            </nz-descriptions-item>
                            <nz-descriptions-item nzTitle="Last stop">
                                {{resolution.last_stop | date: 'yyyy/MM/dd HH:mm'}}
                            </nz-descriptions-item>
                            <nz-descriptions-item *ngIf="resolution.resolver_inputs" nzTitle="Resolver inputs" class="inputs">
                                <div *ngFor="let inputKey of objectKeys(resolution.resolver_inputs)" class="input">
                                    <span class="key">{{ inputKey }}</span>
                                    <span class="value">{{resolution.resolver_inputs[inputKey] | json}}</span>
                                </div>
                            </nz-descriptions-item>
                            <nz-descriptions-item nzTitle="Run count">
                                {{resolution.run_count}} / {{resolution.run_max}}
                            </nz-descriptions-item>
                        </nz-descriptions>
                        <lib-utask-steps-list *ngIf="resolution.steps" [resolution]="resolution"
                            [selectedStep]="selectedStep" (stepChanged)="loadTask(true)">
                        </lib-utask-steps-list>
                    </div>
                    <div nz-col [nzSpan]="16">
                        <nz-alert *ngIf="canStartOver$ | async" nzBanner nzMessage="It appears that the task is stuck. If you're experiencing difficulties or need to correct the inputs, you can simply click the 'Start Over' button to reset and try again"></nz-alert>
                        <lib-utask-steps-viewer [resolution]="resolution" (select)="selectStepFromViewer($event)">
                        </lib-utask-steps-viewer>
                    </div>
                </div>
            </div>
        </lib-utask-box>

        <!-- Resolve & reject boxes -->
        <div nz-row [nzGutter]="16" *ngIf="taskIsResolvable">
            <lib-utask-box nz-col [nzSpan]="12" [header]="{openable: true, init: display.resolution, class: 'success'}">
                <div app-box-header>
                    Resolve this task
                </div>
                <div app-box-content>
                    <lib-utask-inputs-form [formGroup]="validateResolveForm" [inputs]="resolverInputs">
                    </lib-utask-inputs-form>
                    <form nz-form [formGroup]="validateResolveForm" (ngSubmit)="resolveTask()">
                        <nz-form-item nz-row>
                            <nz-form-control>
                                <button type="submit" nz-button nzType="primary" [disabled]="!validateResolveForm.valid"
                                    [nzLoading]="loaders.resolveTask">Resolve</button>
                            </nz-form-control>
                        </nz-form-item>
                    </form>
                    <lib-utask-error-message [data]="errors.resolveTask" *ngIf="errors.resolveTask">
                    </lib-utask-error-message>
                </div>
            </lib-utask-box>
            <lib-utask-box nz-col [nzSpan]="12" [header]="{openable: true, init: display.resolution, class: 'danger'}">
                <div app-box-header>
                    Reject this task
                </div>
                <div app-box-content>
                    <form nz-form [formGroup]="validateRejectForm" (ngSubmit)="rejectTask()">
                        <nz-form-item nz-row>
                            <nz-form-control>
                                <label formControlName="agree" nz-checkbox>
                                    Are you sure you want to reject this request ?
                                </label>
                            </nz-form-control>
                        </nz-form-item>
                        <nz-form-item nz-row>
                            <nz-form-control>
                                <button type="submit" nz-button nzType="danger" [disabled]="!validateRejectForm.valid"
                                    [nzLoading]="loaders.rejectTask">Reject</button>
                            </nz-form-control>
                        </nz-form-item>
                    </form>
                    <lib-utask-error-message [data]="errors.rejectTask" *ngIf="errors.rejectTask">
                    </lib-utask-error-message>
                </div>
            </lib-utask-box>
        </div>

        <!-- Sub tasks box -->
        <lib-utask-box [header]="{openable: true, init: true, class: 'primary'}" *ngIf="haveAtLeastOneChilTask">
            <div app-box-header>
                Sub Tasks
            </div>
            <div app-box-content>
                <lib-utask-tasks-list [meta]="(meta$ | async)" [params]="{
                page_size: 10,
                type: (meta$ | async).user_is_admin ? 'all' : 'own',
                tag: '_utask_parent_task_id=' + taskId
            }" (event)="eventUtask($event)" [options]="listOptions">
                </lib-utask-tasks-list>
            </div>
        </lib-utask-box>

        <!-- Comments box -->
        <lib-utask-box [header]="{openable: true, init: display.comments, class: 'primary'}">
            <div app-box-header>
                Comments - <span class="badge"
                    [ngClass]="{'badge-warning': (task$ | async).comments.length > 0, 'badge-secondary': !(task$ | async).comments || (task$ | async).comments.length === 0}">{{(task$ | async).comments.length}}</span>
                <span *ngIf="loaders.task || loaders.addComment">&nbsp;<i nz-icon nzType="loading"></i></span>
            </div>
            <div app-box-content>
                <nz-list *ngIf="(task$ | async).comments && (task$ | async).comments.length" [nzDataSource]="(task$ | async).comments"
                    [nzRenderItem]="comment" [nzItemLayout]="'horizontal'">
                    <ng-template #comment let-comment>
                        <nz-comment [nzAuthor]="comment.username" [nzDatetime]="comment.created | utaskFromNow">
                            <nz-avatar nz-comment-avatar [nzText]="comment.username[0].toUpperCase()"></nz-avatar>
                            <nz-comment-content>
                                <p>{{ comment.content }}</p>
                            </nz-comment-content>
                        </nz-comment>
                    </ng-template>
                </nz-list>
                <nz-comment>
                    <nz-avatar nz-comment-avatar [nzText]="(meta$ | async).username[0].toUpperCase()"></nz-avatar>
                    <nz-comment-content>
                        <nz-form-item>
                            <textarea [(ngModel)]="comment.content" nz-input [nzAutosize]="{ minRows: 2 }"></textarea>
                        </nz-form-item>
                        <nz-form-item>
                            <button type="submit" nz-button nzType="primary" [nzLoading]="loaders.addComment"
                                [disabled]="!comment.content" (click)="addComment()">
                                Add Comment
                            </button>
                        </nz-form-item>
                    </nz-comment-content>
                </nz-comment>
                <lib-utask-error-message [data]="errors.addComment" *ngIf="errors.addComment"></lib-utask-error-message>
            </div>
        </lib-utask-box>

    </ng-container>


    <ng-container *ngIf="display.restartTask">
        <lib-utask-box [header]="{openable: true, init: true, class: 'success'}">
            <div app-box-header>
                Resolve this task
            </div>
            <div app-box-content>
                <lib-utask-inputs-form [formGroup]="validateResolveForm" [inputs]="resolverInputs">
                </lib-utask-inputs-form>
                <form nz-form [formGroup]="validateResolveForm" (ngSubmit)="restartTask()">
                    <nz-form-item nz-row>
                        <nz-form-control>
                            <button type="submit" nz-button nzType="primary" [disabled]="!validateResolveForm.valid"
                                [nzLoading]="loaders.restartTask">Resolve & start over</button>
                            <button type="button" nz-button nzType="secondary" (click)="display.restartTask = false;"
                                [nzLoading]="loaders.restartTask">Cancel</button>
                        </nz-form-control>
                    </nz-form-item>
                </form>
                <lib-utask-error-message [data]="errors.restartTask" *ngIf="errors.restartTask">
                </lib-utask-error-message>
            </div>
        </lib-utask-box>
    </ng-container>
</ng-container>